﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace xhim.common.Helper
{
    public class ConfigAppHelper
    {
        //<summary>
        ///返回app.config文件中appSettings配置节的value项
        ///</summary>
        ///<param name="strKey"></param>
        ///<returns></returns>
        public static string GetVaule(string strKey)
        {
            return GetVaule(strKey, "app.config");
        }

        public static string GetVaule(string strKey, string filepath)
        {
            ExeConfigurationFileMap file = new ExeConfigurationFileMap { ExeConfigFilename = filepath };
            Configuration config = ConfigurationManager.OpenMappedExeConfiguration(file, ConfigurationUserLevel.None);
            foreach (string key in config.AppSettings.Settings.AllKeys)
            {
                if (key == strKey)
                {
                    return config.AppSettings.Settings[strKey].Value;
                }
            }
            return null;
        }

        ///<summary>
        ///在app.config文件中appSettings配置节增加一对键值对
        ///</summary>
        ///<param name="newKey"></param>
        ///<param name="newValue"></param>
        public static void SetVaule(string newKey, string newValue)
        {
            SetVaule(newKey, newValue, "app.config");
        }

        public static void SetVaule(string newKey, string newValue, string filepath)
        {
            ExeConfigurationFileMap file = new ExeConfigurationFileMap { ExeConfigFilename = filepath };
            Configuration config = ConfigurationManager.OpenMappedExeConfiguration(file, ConfigurationUserLevel.None);
            bool exist = false;
            foreach (string key in config.AppSettings.Settings.AllKeys)
            {
                if (key == newKey)
                {
                    exist = true;
                }
            }
            if (exist)
            {
                config.AppSettings.Settings.Remove(newKey);
            }
            config.AppSettings.Settings.Add(newKey, newValue);
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }
    }
}
